package com.tbvtc.agriculturalcreditchainserver2025.controller.admin;

import com.tbvtc.agriculturalcreditchainserver2025.mapper.AuthMapper;
import com.tbvtc.agriculturalcreditchainserver2025.service.IpfsService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.ImageCompressUtil;
import com.tbvtc.agriculturalcreditchainserver2025.utils.RUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Result;
import io.ipfs.multihash.Multihash;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@CrossOrigin
@RestController
@Tag(name = "上传")

public class uploadController {
    @Autowired
    private IpfsService ipfsService;
    @Autowired
    private AuthMapper authMapper;

    @PostMapping("/upload")
    @Operation(summary = "存储到ipfs")
    public Result upload(@RequestPart("file") MultipartFile file) throws Exception {
        String hashString = ipfsService.uploadToIpfs(file.getBytes());
        log.info("文件上传成功，url值为：{}", hashString);
        return RUtils.success(hashString);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "文件删除")
    public Result delete(@RequestParam("hash") String hash) {
        List<Multihash> multiHashes = ipfsService.rmFromIpfs(hash);
        return RUtils.success(multiHashes);
    }

    @GetMapping("/preview/{hash}")
    @Operation(summary = "文件预览")
    public Result preview(@PathVariable("hash") String hash, HttpServletResponse response) throws IOException {
        long start = System.currentTimeMillis();
        //附件预览
        response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(hash, StandardCharsets.UTF_8));
        byte[] bytes = ipfsService.downFromIpfs(hash);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        byte[] compressedBytes = ImageCompressUtil.compressImage(inputStream, 800, 600, 0.2f);


        if (bytes == null || bytes.length == 0) {
            return RUtils.Err(0, "文件预览失败");
        }
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        long en= System.currentTimeMillis();
        log.info("文件预览耗时：{}ms", en - start);
        return RUtils.success("文件预览成功");
    }


}
